<template>
    <div>
        <el-table :data="paginatedData" style="width: 100%">
            <el-table-column prop="user" label="用户" />
            <el-table-column prop="source" label="来源" />
            <el-table-column prop="curCreateTime" label="数据录入时间" />
            <el-table-column prop="tradingTime" label="交易时间" />
            <el-table-column prop="tradingType" label="交易类型" />
            <el-table-column prop="counterParty" label="交易对方" />
            <el-table-column prop="tradeDescription" label="商品说明" />
            <el-table-column prop="receiptsAndExpenditure" label="收/支" />
            <el-table-column prop="amount" label="金额" />
            <el-table-column prop="status" label="交易状态" />
            <el-table-column prop="orderNumber" label="交易单号" />
            <el-table-column prop="merchantNumber" label="商家单号" />
            <el-table-column prop="remark" label="备注" />
            <el-table-column fixed="right" label="操作" min-width="120">
                <template #header>
                    <div class="displayInlineBlock">操作</div>
                    <div class="displayInlineBlock">
                        <el-icon :color="sortStatus === 'up' ? '#409efc' : ''" style="margin-right: 8px;"
                            @click="sortData('up')">
                            <SortUp />
                        </el-icon>
                        <el-icon :color="sortStatus === 'mid' ? '#409efc' : ''" style="margin-right: 8px;"
                            @click="sortData('mid')">
                            <Sort />
                        </el-icon>
                        <el-icon :color="sortStatus === 'down' ? '#409efc' : ''" @click="sortData('down')">
                            <SortDown />
                        </el-icon>
                    </div>
                </template>
                <template #default="scope">
                    <el-popconfirm confirm-button-text="Yes" cancel-button-text="No" icon-color="#626AEF"
                        title="Are you sure to delete this?" @confirm="deleteRow(scope.row.orderNumber)"
                        @cancel="cancelEvent">
                        <template #reference>
                            <el-button link type="primary">移除</el-button>
                        </template>
                    </el-popconfirm>
                    <!-- <el-button link type="primary" @click.prevent="deleteRow(scope.row.orderNumber)">
                        移除
                    </el-button> -->
                    <el-button link type="primary" v-if="scope.row.ignoreFlag === 0"
                        @click.prevent="ignoreRow(scope.row.orderNumber, true)">
                        忽略
                    </el-button>
                    <el-button link type="primary" v-if="scope.row.ignoreFlag === 1"
                        @click.prevent="ignoreRow(scope.row.orderNumber, false)">
                        取消忽略
                    </el-button>
                    <el-button link type="primary" plain @click="dialogFormVisible = true" v-if="!scope.row.remark">
                        添加备注
                    </el-button>
                    <el-button link type="primary" plain @click="dialogFormVisible = true" v-if="scope.row.remark">
                        修改备注
                    </el-button>
                    <el-dialog v-model="dialogFormVisible" :title="scope.row.remark ? '修改备注' : '添加备注'" width="500">
                        <el-form :model="form">
                            <el-form-item label="备注" :label-width="formLabelWidth">
                                <el-input v-model="form.remark" autocomplete="off" :rows="4" type="textarea" />
                            </el-form-item>
                        </el-form>
                        <template #footer>
                            <div class="dialog-footer">
                                <el-button @click="cancelDialog">取消</el-button>
                                <el-button type="primary" @click="changeRemark(scope.row.orderNumber)">
                                    确定
                                </el-button>
                            </div>
                        </template>
                    </el-dialog>
                </template>
            </el-table-column>
        </el-table>
    </div>
    <div class="paginationDiv">
        <el-pagination layout="prev, pager, next" :total="total" :page-size="pagesize" :current-page="currentPage"
            @current-change="handleCurrentChange" />
    </div>
</template>

<script lang="ts" setup>
import { ref, computed, defineProps, defineEmits, watch, reactive } from "vue";
import { changeIgnoreStatusAPI, deleteConsumptionAPI, changeRemarkAPI } from "src/httpApi/consumptionHttp";
import { ElMessage, ElMessageBox } from 'element-plus'

const emit = defineEmits(["getParamsData"]);

// 定义 Props 类型
const props = defineProps<{
    tableData: any[];
}>();

const formLabelWidth = '60px'
const search = ref(""); // 使用 ref() 包装
const pagesize = ref(10); // 指定展示多少条
const currentPage = ref(1); // 默认展示第几页
const total = ref(0);
const dialogFormVisible = ref(false);
// descending下行 ascending提升 
const sortStatus = ref("");

const form = reactive({
    remark: '',
})

// 计算过滤后的数据
const filteredData = computed(() => {
    return props.tableData.filter(
        (data: any) => !search.value ||
            data.user.toLowerCase().includes(search.value.toLowerCase()) ||
            data.tradeDescription.toLowerCase().includes(search.value.toLowerCase())
    );
});

// 计算分页后的数据
const paginatedData = computed(() => {
    const start = (currentPage.value - 1) * pagesize.value;
    const end = currentPage.value * pagesize.value;
    return filteredData.value.slice(start, end);
});

// 处理页码变化
const handleCurrentChange = (val: number) => {
    currentPage.value = val;
};

// 点击删除函数执行
const deleteRow = async (data: number) => {
    const params = {
        orderNumber: data,
    };
    const res = await deleteConsumptionAPI(params);
    if (res.code === 200) {
        ElMessage({
            message: '删除成功！',
            type: 'success',
        })
        emit("getParamsData");
    } else {
        ElMessage({
            message: '删除失败！',
            type: 'error',
        })
    }
}

// 点击忽略和取消忽略的函数执行
const ignoreRow = async (data: number, bool: boolean) => {
    const params = {
        orderNumber: data,
        ignoreFlag: bool
    };
    const res = await changeIgnoreStatusAPI(params);
    if (res.code === 200) {
        ElMessage({
            message: '状态修改成功！',
            type: 'success',
        })
        emit("getParamsData");
    } else {
        ElMessage({
            message: '状态修改失败！',
            type: 'error',
        })
    }
}

// 添加备注点击确认
const changeRemark = async (data: number) => {
    console.log('changeRemark!', form.remark)
    if (data) {
        dialogFormVisible.value = false;
        const res = await changeRemarkAPI(form);
        form.remark = '';
    }
}

// 添加备注点击取消
const cancelDialog = () => {
    dialogFormVisible.value = false;
    form.remark = '';
}

// 移除二次确认取消函数调用
const cancelEvent = () => {
    console.log('cancel!')
}

const sortData = (status: string) => {
    sortStatus.value = status;
    switch (status) {
        case 'up':
            // 升序排序，按金额字段排序
            props.tableData.sort((a, b) => a.amount - b.amount);
            break;
        case 'down':
            // 降序排序，按金额字段排序
            props.tableData.sort((a, b) => b.amount - a.amount);
            break;
        case 'mid':
            // 恢复默认排序（例如按创建时间排序）
            props.tableData.sort((a, b) => new Date(a.tradingTime).getTime() - new Date(b.tradingTime).getTime());
            break;
        default:
            break;
    }
};


// 监听过滤后的数据变化以更新 total
watch(
    filteredData,
    (newData) => {
        total.value = newData.length;
    },
    { immediate: true }
);
</script>

<style scoped>
.paginationDiv {
    width: 100%;
    display: flex;
    justify-content: right;
}

::v-deep(.el-overlay ){
    background-color: rgba(0, 0, 0, 0);
}

.displayInlineBlock {
    display: inline-block;
}
</style>
